package com.yourenbang.lingyun.transaction.job.handler;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.annotation.XxlJob;
import com.xxl.job.core.log.XxlJobLogger;
import com.yourenbang.lingyun.constants.enums.ChannelIdEnums;
import com.yourenbang.lingyun.constants.enums.PlatNoEnums;
import com.yourenbang.lingyun.constants.enums.pay.PayFromEnum;
import com.yourenbang.lingyun.constants.enums.pay.PayTypeEnum;
import com.yourenbang.lingyun.core.message.Result;
import com.yourenbang.lingyun.core.util.KLog;
import com.yourenbang.lingyun.core.util.encrypt.mapai.DecryptUtil;
import com.yourenbang.lingyun.domain.Merchant21;
import com.yourenbang.lingyun.domain.Merchant21Example;
import com.yourenbang.lingyun.domain.Terminal21;
import com.yourenbang.lingyun.domain.Terminal21Example;
import com.yourenbang.lingyun.mapper.Merchant21Mapper;
import com.yourenbang.lingyun.mapper.Terminal21Mapper;
import com.yourenbang.lingyun.transaction.job.model.dto.HsmpTransactionQueryResult;
import com.yourenbang.lingyun.transaction.mapper.TransactionPayTransactionMapper;
import com.yourenbang.lingyun.transaction.util.PayTransactionUtil;
import com.yourenbang.lingyun.transaction.web.service.PayTransactionFormatService;
import com.yourenbang.lingyun.transaction.web.service.pay.klks.PayEposService;
import com.yourenbang.lingyun.transaction.web.service.yxy.YxyTradeService;
import com.yourenbang.merchant.api.model.dto.CreateRewardYxyDTO;
import com.yourenbang.merchant.api.service.yxy.MerchantYxyApiService;
import com.yourenbang.merchant.api.service.yxy.MerchantYxyRewardApiService;
import com.yourenbang.transaction.api.model.vo.pay.PayTransaction;
import com.yourenbang.transaction.api.service.pay.PayTypeApiService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.Objects;

@Component
@Slf4j
public class HuiShangMaPaiTransactionQueryHandler {
    @Autowired
    private PayTypeApiService payTypeApiService;
    @Resource(name = "hsmpTransactionFormatService")
    PayTransactionFormatService payTransactionFormatService;
    @Autowired
    YxyTradeService yxyTradeService;
    @Autowired
    MerchantYxyApiService merchantYxyApiService;
    @Autowired
    private PayEposService payEposService;

    /**
     * 惠商码牌订单列表查询
     *
     * @param params 定时任务执行参数
     */
    @XxlJob("hsmpTransactionQueryHandler")
    public ReturnT<String> transactionQuery(String params) {
        LocalDateTime endTime = LocalDateTime.now(), startTime = endTime.minusMinutes(5);
        boolean test = false;
        String decryData = "";
        if (StringUtils.isNotEmpty(params)) {
            JSONObject jParam = JSONObject.parseObject(params);
            if (jParam.containsKey("interval")) {
                startTime = endTime.minusMinutes(jParam.getInteger("interval"));
            }
            if (jParam.containsKey("timeStart") && StringUtils.isNotEmpty(jParam.getString("timeStart"))) {
                startTime = LocalDateTimeUtil.parse(jParam.getString("timeStart"), DatePattern.NORM_DATE_PATTERN);
            }
            if (jParam.containsKey("timeEnd") && StringUtils.isNotEmpty(jParam.getString("timeEnd"))) {
                endTime = LocalDateTimeUtil.parse(jParam.getString("timeEnd"), DatePattern.NORM_DATE_PATTERN);
            }
            if (jParam.containsKey("test") && jParam.getBoolean("test")) {
                test = true;
                decryData = jParam.getString("data");
            }
        }
        if (!test) {
            Map<String, String> payParams = payTypeApiService.getPayParams(PayTypeEnum.HUISHANGMAPAI, PayFromEnum.merchant);
            JSONObject jParam = new JSONObject();
            jParam.put("merchantId", 1000);
            jParam.put("startTime", LocalDateTimeUtil.format(startTime, DatePattern.NORM_DATE_PATTERN));
            jParam.put("endTime", LocalDateTimeUtil.format(endTime, DatePattern.NORM_DATE_PATTERN));
            String result = HttpUtil.post(payParams.get("api") + "/api/merchant-order/openApi/api/orderList", jParam.toJSONString());
            log.info("惠商码牌订单列表查询，{}，{}", result, jParam);
            JSONObject jResult = JSONObject.parseObject(result);
            if (!jResult.getBoolean("success")) {
                if (jResult.getString("msg").contains("数据为空")) {
                    XxlJobLogger.log("惠商码牌订单列表数据为空:{}", result);
                    return ReturnT.SUCCESS;
                } else {
                    XxlJobLogger.log("惠商码牌订单列表查询失败:{}", result);
                    return ReturnT.FAIL;
                }
            }
            try {
                decryData = DecryptUtil.decrypt(jResult.getJSONObject("data").getString("bizContent"), payParams.get("privateKey"));
                log.info("惠商码牌订单列表查询解密后，{}", decryData);
                XxlJobLogger.log("惠商码牌订单列表查询解密后，{}", decryData);
            } catch (Exception e) {
                XxlJobLogger.log("查询商户码牌失败:{}", result);
                return ReturnT.FAIL;
            }
        }
        JSONArray queryResult = JSONArray.parseArray(decryData);
        if (!queryResult.isEmpty()) {
            for (Object item : queryResult) {
                HsmpTransactionQueryResult orderInfo = JSONObject.parseObject(item.toString(), HsmpTransactionQueryResult.class);
                PayTransaction payTransaction = payTransactionFormatService.payTransactionFormat(JSONObject.parseObject(JSONObject.toJSONString(orderInfo)));
                if (Objects.isNull(payTransaction)) {
                    XxlJobLogger.log("商户不存在，跳过:{}", JSONObject.toJSONString(orderInfo));
                    continue;
                }

                PayTransaction payTransactionSaved = yxyTradeService.saveTrade(payTransaction);
                // 重复交易不继续执行
                if (Objects.nonNull(payTransactionSaved)) {
                    // 计入分润
                    payEposService.profitOpt(payTransaction);
                    // 私信调用
                    payEposService.sendTransactionLetter(payTransaction);
                    // 检查满10万改费率
                    merchantYxyApiService.checkMerchantDiscountRate(payTransaction.getMerchantId());
                }
            }
        } else {
            XxlJobLogger.log("查询商户码牌结果为空");
        }
        return ReturnT.SUCCESS;
    }
}
